/**
 * URLFetcher.java
 * 
 * FreeZzaph is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * FreeZzaph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.
 */
package freezzaph.plugins;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.CharBuffer;

import freezzaph.exceptions.URLFetchException;

/**
 * Convenience class to download data from a URL.
 * 
 * @author FreeZzaph
 */
public class URLFetcher {
	
	protected static final int BUFFER_SIZE = 8192;
	
	/**
	 * Downloads a URL into a String.
	 * 
	 * @param url the URL to download
	 * @return the String containing the data
	 * @throws URLFetchException if there's a problem fetching
	 * data from the URL.
	 */
	public static String fetch(URL url) throws URLFetchException {
		
		// Open connection
		URLConnection conn;
		try {
			 conn = url.openConnection();
			conn.setConnectTimeout(10000);
		} catch (IOException ioe) {
			throw new URLFetchException(
					"Could not open connection to URL",
					ioe, url);
		}
		
		// Encapsulate URL's InputStream in a BufferedReader
		BufferedReader urlReader;
		try {
			urlReader = new BufferedReader(
					new InputStreamReader(
							conn.getInputStream(), "utf8"));
		} catch (IOException ioe) {
			throw new URLFetchException(
					"I/O exception occured while opening InputStream of URL",
					ioe, url);
		}
		
		// Read characters from the URL into a charbuffer and
		// append these to a StringBuilder
		CharBuffer cb = CharBuffer.allocate(BUFFER_SIZE);
		StringBuilder sb = new StringBuilder();
		try {
			while ((urlReader.read(cb)) != -1) {
				cb.rewind();
				sb.append(cb);
				cb.rewind();
			}
		} catch (IOException ioe) {
			throw new URLFetchException(
					"I/O exception occured while reading data from URL",
					ioe, url);
		}
		
		// Return the resulting string
		return sb.toString();
	}
	
	/**
	 * Downloads a URL into a ByteArrayOutputStream. This choice
	 * was made because of the convenience of the ByteArrayOutputStream
	 * when it comes to dealing with other OutputStreams. If only the
	 * byte data itself is required, see the
	 * {@link ByteArrayOutputStream#toByteArray() toByteArray()} method
	 * of the ByteArrayOutputStream class.
	 * 
	 * @param url
	 * @return a ByteArrayOutputStream containing the URLs bytes
	 * @throws URLFetchException if there's a problem fetching
	 * data from the URL.
	 */
	public static ByteArrayOutputStream fetchBytes(URL url) throws URLFetchException {
		
		// Open the URL's InputStream
		InputStream is;
		try {
			is = url.openStream();
		} catch (IOException ioe) {
			throw new URLFetchException(
					"I/O exception occured while opening InputStream of URL",
					ioe, url);
		}
		
		// Create buffer
		byte[] bb = new byte[BUFFER_SIZE];
		
		// Create ByteArrayOutputStream
		ByteArrayOutputStream bytebuffer = new ByteArrayOutputStream(BUFFER_SIZE);

		// Read bytes into the buffer and write them
		// into the ByteArrayOutputStream.
		int read;
		try {
			while ((read = is.read(bb)) != -1) {
				bytebuffer.write(bb, 0, read);
			}
		} catch (IOException ioe) {
			throw new URLFetchException(
					"I/O exception occured while reading data from URL",
					ioe, url);
		}
		
		// Return the ByteArrayOutputStream
		return bytebuffer;
	}

}
